<?php
/**
 * 《用车安排》实现类
 *
 * @author 孙晓晔
 * @version $Id: Car.class.php 1033 2010-03-25 11:26:55Z sunxy $
 */
require_once(dirname(__FILE__) . '/CarUtil.class.php');

class Plan extends CarUtil {
	public $tbl = Constant::tbl_car_plan;

	public $status = array(
		'-' => '请选择',
		'1' => '等待出发',
		'2' => '已经出发',
		'3' => '完成用车',
		'5' => '暂停用车',
		'6' => '取消用车',
	
		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'car' => '车辆',
		'emp' => '司机',
		'km' => '公里数',
		't1' => '出发时间',
		'1' => '创建时间',
		'2' => '更新时间',
	);

	public $groupby = array(
		'-' => '请选择',
		'car' => '车辆',
		'driver' => '司机',
		'emp' => '派车人',
		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);

	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-7 day'));

		$controller->display($request, 'car/plan/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == 'km') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['km'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$car_s = $this->_input($request['car_s']);
		$driver_s = $this->_input($request['driver_s']);

		$date1_s = $request['date1_s'];
		$date2_s = $request['date2_s'];

		$where = " WHERE 1=1";

		if (!empty($car_s)) {
			$where .= " AND car = '" . $car_s . "'";
		}

		if (!empty($driver_s)) {
			$where .= " AND driver = '" . $driver_s . "'";
		}

		if (!empty($date1_s)) {
			$where .= " AND t1 >= '" . $date1_s . "'";
		}

		if (!empty($date2_s)) {
			$where .= " AND t2 < '" . $date2_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row['num'] = $this->_num($row['id']);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$row['is_delete'] = $this->_is_delete($row);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'car/plan/list');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function my($controller, $request) {

		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->display($request, 'car/plan/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$car = $this->_input($request['car']);
		$driver = $this->_input($request['driver']);

		$address = $request['address'];
		$t1 = $request['t1'];
		$t2 = $request['t2'];

		$content = addslashes($request['content']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(car, driver, address, t1, t2, content, emp, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $car, $driver, $address, $t1, $t2, $content, $emp, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);
		
		$request['id_s'] = $db->insert_id();

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function carPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		$car = $this->_input($request['car']);
		$driver = $this->_input($request['driver']);

		$address = $request['address'];
		$t1 = $request['t1'];
		$t2 = $request['t2'];

		$content = addslashes($request['content']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(car, driver, address, t1, t2, content, emp, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $car, $driver, $address, $t1, $t2, $content, $emp, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);
		$plan = $db->insert_id();

		$content = addslashes($request['content']);

		$this->_car($controller, $request, $id, $plan);

		return true;
	}

	function _car($controller, $request, $id, $plan) {
		require_once(dirname(__FILE__) . '/Requirement.class.php');
		$aa = new Requirement();
		
		$aa->_car($controller, $request, $id, $plan);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'car/plan/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$car = $this->_input($request['car']);
		$driver = $this->_input($request['driver']);

		$address = $request['address'];
		$t1 = $request['t1'];
		$t2 = $request['t2'];
		
		$km1 = $request['km1'];
		$km2 = $request['km2'];
		$km = intval($km2) - intval($km1);

		$content = addslashes($request['content']);
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET car = '%s', driver = '%s', address = '%s', t1 = '%s', t2 = '%s', km1 = '%s', km2 = '%s', km = '%s'";
		$fmt .= ", content = '%s', emp = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $car, $driver, $address, $t1, $t2, $km1, $km2, $km, $content, $emp, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function finish($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'car/plan/finish');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function finishPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$km1 = $request['km1'];
		$km2 = $request['km2'];
		$km = intval($km2) - intval($km1);

		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET km1 = '%s', km2 = '%s', km = '%s', content = '%s', status = '3', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $km1, $km2, $km, $content, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		require_once(dirname(__FILE__) . '/Car.class.php');
		$car = new Car();
		$controller->assign_by_ref('car', $car->_view($row['car']));

		$controller->assign_by_ref('requirement', $this->_requirement($row['id']));
		
		if (!empty($request['print'])) {
			$controller->display($request, 'car/plan/view_print');
			return true;
		}

		$controller->display($request, 'car/plan/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['car_t'] = Name::car($row['car']);
		$row['driver_t'] = Name::emp($row['driver']);
		$row['date'] = $this->_date($row['t1'], $row['t2']);

		$row = $this->_view_t($row);

		return $row;
	}
	
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
			
			$row = $this->id($this->tbl, $id);
			
			if ($this->_is_delete($row)) {
				$fmt = "DELETE FROM %s WHERE id = '%s'";
				$sql = sprintf($fmt, $this->tbl, $id);
				// debug($sql);
				$db->query($sql);
			}
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}

		if ($row['status'] > 1) {
			return false;
		}

		if ($row['emp'] == $_SESSION['id']) {
			return true;
		}

		return false;
	}

	function _driver($emp) {
		$row = $this->id(Constant::tbl_emp, $emp);
		$ret = $row['name'];

		if (!empty($row['mobile']) && !empty($row['short'])) {
			return sprintf("%s(%s/%s)", $row['name'], $row['mobile'], $row['short']);
		}

		return sprintf("%s(%s)", $row['name'], $row['mobile']);
	}

	function _num($id) {
		$requirement = $this->_requirement($id);
		if (is_array($requirement)) {
			return count($requirement);
		}

		return 0;
	}

	function _requirement($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE status = '3' AND plan = '%s' ORDER BY id";
		$sql = sprintf($fmt, Constant::tbl_car_requirement, $id);
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['emp_t'] = Name::emp($row['emp']);

			$row['date'] = $this->_time($row['t1'], $row['t2']);

			$ret[] = $row;
		}

		return $ret;
	}	

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat_group($controller);

		// $controller->assign('t1', strtotime('-1 month'));
		// $controller->assign('t2', strtotime('+1 day'));

		$num = array(
			'1' => '按次数',
			'2' => '按里程',
		);
		$controller->assign('num_option', $num);

		$controller->display($request, 'car/plan/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function groupby_dd($px) {
		if ($px == '1') {
			return "DATE_FORMAT(t1, '%Y-%m-%d %H')";
		}

		if ($px == '2') {
			return "DATE_FORMAT(t1, '%Y-%m-%d')";
		}

		if ($px == '3') {
			return "DATE_FORMAT(t1, '%Y-%m')";
		}

		return $px;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$num_s = $request['num_s'];
		if (!empty($num_s) && $num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(km) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(km) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp' || $px == 'driver') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'car') {
			$row['a'] = Name::car($row['a']);
		} else {
		
			$row = $this->_name_t($row, $px);
		}

		return $row;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_code($controller, $request) {

		$data = $this->_ajax_code($request);
		echo json_encode($data);
	}

	function _ajax_code($request) {
		$q = $request['q'];
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND code LIKE '%s'";
		$sql = sprintf($fmt, $this->tbl, $q . "%");
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['car_t'] = Name::car($row['car']);
			$row['driver_t'] = Name::emp($row['driver']);

			$row['date'] = $this->_date($row['t1'], $row['t2']);

			$ret[] = $row;
		}

		return $ret;
	}

	function ajax_valid($controller, $request) {
		$car = $this->_input($request['car']);
		$driver = $this->_input($request['driver']);

		$t1 = $request['t1'];
		$t2 = $request['t2'];

		$ret = array();
		$a = $this->_valid_car($t1, $t2, $car);
		if (!$a) {
			$ret['status'] = 1;
			echo json_encode($ret);
			return false;
		}

		$b = $this->_valid_driver($t1, $t2, $driver);
		if (!$b) {
			$ret['status'] = 2;
			echo json_encode($ret);
			return false;
		}

		$ret['status'] = 3;

		echo json_encode($ret);
	}

	/**
	 *
	 */
	function _valid_time($row, $t1, $t2) {
		if (strtotime($t1) > strtotime($row['t1']) && strtotime($t1) < strtotime($row['t2'])) {
			return false;
		}

		if (strtotime($t2) > strtotime($row['t1']) && strtotime($t2) < strtotime($row['t2'])) {
			return false;
		}

		if (strtotime($t1) <= strtotime($row['t1']) && strtotime($t2) >= strtotime($row['t2'])) {
			return false;
		}

		return true;
	}

	function _valid_car($t1, $t2, $car) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE car = '%s' AND status = 1 AND createtime > DATE_ADD(now(), INTERVAL -20 DAY)";
		$sql = sprintf($fmt, $this->tbl, $car);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			if (!$this->_valid_time($row, $t1, $t2)) {
				return false;
			}
		}

		return true;
	}

	function _valid_driver($t1, $t2, $driver) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE driver = '%s' AND status = 1 AND createtime > DATE_ADD(now(), INTERVAL -20 DAY)";
		$sql = sprintf($fmt, $this->tbl, $driver, $t1, $t2);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			if (!$this->_valid_time($row, $t1, $t2)) {
				return false;
			}
		}

		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function reason($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		clean($this->tbl . "_id_" . $id);
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->assign_by_ref('requirement', $this->_requirement($row['id']));

		$controller->display($request, 'car/plan/reason');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function reasonPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$reason = addslashes($request['reason']);

		$status = $request['status'];

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET reason = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $reason, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$fmt = "UPDATE %s SET reason = '%s', status = '%s', modifytime = now() WHERE status = '3' AND plan = '%s'";
		$sql = sprintf($fmt, Constant::tbl_car_requirement, $reason, $status, $id);
		$db->query($sql);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function status_continue($controller, $request) {

		return $this->status_restart($controller, $request);
	}

	function status_restart($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, '1', $id);
		// debug($sql);
		$db->query($sql);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 * 定时运行，自动更新等待出发的用车安排
	 */
	function status_update($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND createtime > DATE_ADD(now(), INTERVAL -7 DAY)";
		// $fmt = "SELECT * FROM %s WHERE status = '1'";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if (strtotime($row['t1']) > time()) {
				echo "S";
				continue;
			}

			if ($this->_num($row['id']) == 0) {
				continue;
			}

			echo ".";

			$fmt = "UPDATE %s SET status = '2' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $row['id']);
			// debug($sql);
			$db->query($sql);
		}

		echo "\n" . $_REQUEST['do'] . "\n";

		logdate($controller, $request);
		return true;
	}
	
	function _list() {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE status = '1' ORDER BY id DESC LIMIT 8";
		$sql = sprintf($fmt, $this->tbl);
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['car_t'] = Name::car($row['car']);
			$row['driver_t'] = Name::emp($row['driver']);

			$row['date'] = $this->_date($row['t1'], $row['t2']);

			$ret[] = $row;
		}

		return $ret;
	}

	function tj_daily($controller, $request) {
		$this->pretreat($controller);

		$request['tpl'] = "html4";

		$from = $this->email;
		$to = 'sunxy@tecmold.com';

		$subject = '司机出勤申情况';

		$this->result_s = 20;
		$this->groupby_s = 'driver';

		$body = $this->_tj_a($controller, $request);

		$this->mail_html($from, $to, $subject, $body);

		logdate($controller, $request);
		return true;
	}
}
?>
